package com.hopechart.micro.common.exception;

import com.hopechart.micro.common.constant.Response;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *      全局异常处理<br/>
 *      spring.mvc.throw-exception-if-no-handler-found=true
 *      spring.resources.add-mappings=false
 * </p>
 *
 * @author daijiang@hopechart.com
 * @version V1.0.0
 * @date 2017-11-29 10:27
 * @copyright 杭州鸿泉数字设备有限公司
 */
@ResponseBody
@ControllerAdvice(basePackages = "com.hopechart.micro.web.controller.admin")
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Response exception(Exception ex) {
        String message = "服务器发生未知异常";
        ErrorCode code = ErrorCode.INNER;

        if (ex instanceof Throwable) {
            if (ex instanceof org.springframework.web.servlet.NoHandlerFoundException) {
                code = ErrorCode.HTTP_STATE_404;
                message = ErrorCode.HTTP_STATE_404.getMessage();
            } else if (ex instanceof BusinessException) {
                BusinessException businessException = (BusinessException) ex;
                message = businessException.getMessage();
                code = businessException.getCode();
            } else if (ex instanceof MissingServletRequestParameterException) {
                message = ErrorCode.PARAM_MISSING.getMessage() + "，参数名："
                        + ((MissingServletRequestParameterException) ex).getParameterName();
                code = ErrorCode.PARAM_MISSING;
            } else if (ex instanceof HttpRequestMethodNotSupportedException) {
                message = ErrorCode.REQUEST_METHOD.getMessage() + "，" + ex.getMessage();
                code = ErrorCode.REQUEST_METHOD;
            } else if (ex instanceof BindException) {
                message = ErrorCode.PARAM_TYPE.getMessage() + "，"
                        + ((BindException) ex).getFieldError().getDefaultMessage();
                code = ErrorCode.PARAM_TYPE;
            } else {
                message = ex.getMessage();
            }
        }
        return new Response(code.getCode(), message);
    }
}